package com.ruoyi.initialdata.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.initialdata.tool.DataToIndex;
import com.ruoyi.initialdata.tool.SQLParser;
import com.ruoyi.initialdata.tool.XmlParser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.initialdata.domain.InitialDataTable1;
import com.ruoyi.initialdata.service.IInitialDataTable1Service;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 原始数据信息Controller
 *
 * @author zry
 * @date 2023-05-11
 */
@RestController
@RequestMapping("/ruoyi-initialdata/initialdata")
public class InitialDataTable1Controller extends BaseController {
    @Autowired
    private IInitialDataTable1Service initialDataTable1Service;


    /**
     * 导出模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<InitialDataTable1> util = new ExcelUtil<>(InitialDataTable1.class);
        util.importTemplateExcel(response, "原始数据信息");
    }

    /**
     * 导入数据
     */
    @Log(title = "原始数据管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ruoyi-initialdata:initialdata:add')")
    @PostMapping("/importData")
    public AjaxResult importData(String selectedType, MultipartFile file, boolean updateSupport, boolean isclearData) throws Exception {
        ExcelUtil<InitialDataTable1> util = new ExcelUtil<>(InitialDataTable1.class);
        InputStream inputStream = file.getInputStream();
        if (selectedType.equals("sql")) {
            SQLParser sqlParser = new SQLParser();
            String sql = null;
            try {
                sql = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
                // System.out.println(sql);
                List<InitialDataTable1> initialdataList = sqlParser.parseInsertStatements(sql);
                System.out.println(initialdataList);
                String operName = getUsername();
                String message = initialDataTable1Service.importInitialData(initialdataList, updateSupport, isclearData, operName);
                return AjaxResult.success(message);
            } catch (Exception e) {
                // 处理异常
                e.printStackTrace();
                return AjaxResult.error("导入失败：" + e.getMessage());
            }
        } else if (selectedType.equals("excel")) {
            List<InitialDataTable1> initialdataList2 = util.importExcel(inputStream);
            System.out.println(initialdataList2);
            String operName = getUsername();
            String message = initialDataTable1Service.importInitialData(initialdataList2, updateSupport, isclearData, operName);
            return AjaxResult.success(message);
        } else if (selectedType.equals("xml")) {
            try {
                // 创建临时文件
                File tempFile = File.createTempFile("temp", ".xml");

                // 将MultipartFile的输入流复制到临时文件
                try (OutputStream outputStream = Files.newOutputStream(tempFile.toPath())) {
                    FileCopyUtils.copy(inputStream, outputStream);
                }

                // 获取临时文件的路径
                String tempFilePath = tempFile.getAbsolutePath();

                // 调用parseXmlFile处理临时文件路径
                XmlParser xmlParser = new XmlParser();
                List<InitialDataTable1> initialdataList3 = xmlParser.parseXmlFile(tempFilePath);
                // 删除临时文件
                tempFile.delete();

                System.out.println(initialdataList3);
                String operName = getUsername();
                String message = initialDataTable1Service.importInitialData(initialdataList3, updateSupport, isclearData, operName);
                return AjaxResult.success(message);
            } catch (Exception e) {
                // 处理异常
                e.printStackTrace();
                return AjaxResult.error("导入失败：" + e.getMessage());
            }
        } else {
            //System.out.println("initialdataList");
            return AjaxResult.error("不支持的文件类型");
        }
    }

    /**
     * 查询原始数据信息列表
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-initialdata:initialdata:list')")
    @GetMapping("/list")
    public TableDataInfo list(InitialDataTable1 initialDataTable1) {
        startPage();
        List<InitialDataTable1> list = initialDataTable1Service.selectInitialDataTable1List(initialDataTable1);
        return getDataTable(list);
    }

    /**
     * 导出原始数据信息列表
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-initialdata:initialdata:export')")
    @Log(title = "原始数据信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InitialDataTable1 initialDataTable1) {
        List<InitialDataTable1> list = initialDataTable1Service.selectInitialDataTable1List(initialDataTable1);
        ExcelUtil<InitialDataTable1> util = new ExcelUtil<InitialDataTable1>(InitialDataTable1.class);
        util.exportExcel(response, list, "原始数据信息数据");
    }

    /**
     * 获取原始数据信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-initialdata:initialdata:query')")
    @GetMapping(value = "/{dataId}")
    public AjaxResult getInfo(@PathVariable("dataId") Long dataId) {
        return success(initialDataTable1Service.selectInitialDataTable1ByDataId(dataId));
    }

    /**
     * 新增原始数据信息
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-initialdata:initialdata:add')")
    @Log(title = "原始数据信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InitialDataTable1 initialDataTable1) {
        return toAjax(initialDataTable1Service.insertInitialDataTable1(initialDataTable1));
    }

    /**
     * 修改原始数据信息
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-initialdata:initialdata:edit')")
    @Log(title = "原始数据信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InitialDataTable1 initialDataTable1) {
        return toAjax(initialDataTable1Service.updateInitialDataTable1(initialDataTable1));
    }

    /**
     * 删除原始数据信息
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-initialdata:initialdata:remove')")
    @Log(title = "原始数据信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dataIds}")
    public AjaxResult remove(@PathVariable Long[] dataIds) {
        return toAjax(initialDataTable1Service.deleteInitialDataTable1ByDataIds(dataIds));
    }

    /**
     * 初始化指标表
     */

    @Autowired
    private DataToIndex dataToIndex;

    @PostMapping("/dataToIndex")
    public AjaxResult dataToIndex() {
        try {
            // 在该方法中实现初始化指标表的逻辑
            dataToIndex.processData();

            return AjaxResult.success("指标表初始化成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("指标表初始化失败");
        }
    }
}
